﻿using System;
using System.Linq;
using System.Web.Caching;
using Microsoft.Practices.ServiceLocation;
using Pap.Core.CronJobs;
using Pap.Core.Logging;
using Pap.Data.Abstraction.Utils;
using Pap.Services;
using Pap.Services.WorkflowEngine;
using Pap.Data;
using System.Configuration;
using System.IO;

namespace Pap.Web.Utils.CronJobs
{
    /// <summary>
    /// 
    /// </summary>
    public class DBBackupCornJob : ICronJob
    {

        private IAdministrationRepository _AdminRepo;

        public DBBackupCornJob(IAdministrationRepository AdminRepo)
        {
            _AdminRepo = AdminRepo;
        }

        /// <summary>
        /// Gets the eexcution time.
        /// </summary>
        /// <returns>returns DBBackup Execution Time</returns>
        private TimeSpan GetEexcutionTime()
        {
            Guid committeeID = _AdminRepo.FindCommittees(committee => true).FirstOrDefault().CommitteeID;

            DateTime execTime = DateTime.Parse(_AdminRepo.GetSettingValue(committeeID,
                                                                    SettingKeys.DatabaseBackupTime));

            // if the processing time already passed
            //return tomorrow's execution time
            if (execTime > DateTime.Now)
                return execTime.TimeOfDay;
            return execTime.AddDays(1).TimeOfDay;
        }

        private String GetDBStoreLocation()
        { 
             return ConfigurationManager.AppSettings["DBBackupRstoreLocation"];
        }

        /// <summary>
        /// Gets the sliding time.
        /// </summary>
        public TimeSpan SlidingTime
        {
            get
            {
                return GetEexcutionTime();
            }
        }
        /// <summary>
        /// Gets the name of the job.
        /// </summary>
        /// <value>
        /// The name of the job.
        /// </value>
        public string JobName
        {
            get
            {
                return "BackupDatabase";
            }
        }

        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            try
            {
                string storeLocation = GetDBStoreLocation();
                string fileName = Path.GetFileNameWithoutExtension(storeLocation) + DateTime.Now.ToString("ddMMMyyyy");
                storeLocation = Path.Combine(Path.GetDirectoryName(storeLocation), fileName + Path.GetExtension(storeLocation));
                _AdminRepo.BackupDatabase(storeLocation);
            }
            catch (Exception exp)
            {
                ServiceLocator.Current.GetInstance<ILog>().RaiseError(exp);
            }
        }
    }
}
